package com.leo.chapter08;

import java.util.concurrent.*;

/**
 * 在单线程的Executor中，一个任务将另一个任务提交到同一个Executor中，并等待这个任务的提交结果，然后发生的死锁
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class ThreadDeadLock {
    static ExecutorService exec = Executors.newSingleThreadExecutor();
//    static ExecutorService exec = Executors.newFixedThreadPool(2);

    static class RenderPageTask implements Callable<String>{
        @Override public String call() throws Exception {
            Future<String> header, footer;
            header = exec.submit(new LoadFileTask("header.html"));
            footer = exec.submit(new LoadFileTask("footer.html"));
            String page = renderBody();
            return header.get() + page + footer.get();
        }

        private String renderBody() throws InterruptedException {
            System.out.println("render body start");
            Thread.sleep(1000);
            System.out.println("render body stop");
            return " body ";
        }
    }

    static class LoadFileTask implements Callable<String> {
        String s;
        public LoadFileTask(String s) {
            this.s = s;        }

        @Override public String call() throws Exception {
            System.out.println("render " + s + " start");
            Thread.sleep(1000);
            System.out.println("render " + s + " stop");
            return s;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ///没有提交到同一个Exec，不会死锁
//        FutureTask<String> target = new FutureTask<>(new RenderPageTask());
//        new Thread(target).start();
//        System.out.println(target.get());
        ///提交到同一个exec，会死锁
        RenderPageTask renderPageTask = new RenderPageTask();
        Future<String> future = ThreadDeadLock.exec.submit(renderPageTask);
        System.out.println(future.get());
        exec.shutdown();
    }
}
